package com.rslai.base.tool.servertest.intercept;

import com.alibaba.fastjson.JSONObject;
import com.rslai.base.tool.servertest.model.KeyValueStore;
import com.rslai.base.tool.servertest.util.Util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class ParamIgnoreInterceptor extends ParameterInterceptor {
    private static final String IGNORE_PARAM = "[IGNORE]";

    protected List<KeyValueStore> convert(List<KeyValueStore> params) {
        if (params != null) {
            ArrayList<KeyValueStore> list = new ArrayList(params);
            for (KeyValueStore kvs : params) {
                if (Util.isJson(kvs.getValue())) {
                    kvs.setValue(removeElement((String) kvs.getValue()));
                } else if ("[IGNORE]".equals(kvs.getValue())) {
                    list.remove(kvs);
                }
            }

            return list;
        }
        return params;
    }

    protected boolean support(List<KeyValueStore> params) {
        if (params != null) {
            for (KeyValueStore kvs : params) {
                if (("[IGNORE]".equals(kvs.getValue())) || ((Util.isJson(kvs.getValue())) && (((String) kvs.getValue()).contains("[IGNORE]")))) {
                    return true;
                }
            }
        }
        return false;
    }

    private String removeElement(String json) {
        Map map = null;
        try {
            map = (Map) JSONObject.parse(json);
        } catch (Exception e) {
            return json;
        }
        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            if ("[IGNORE]".equals(entry.getValue())) {
                iterator.remove();
            }
        }
        return JSONObject.toJSONString(map);
    }
}
